 package com.atguigu.juc;

 import java.security.PublicKey;

 /**
 * @author ：MJS
 * @date ：Created in 2021/4/24  9:23
 * @description：有一个初始变量为0的变量，现有两个线程对该变量操作
 * 一个线程对变量加1，一个线程对变量减1，实现来回交替十次
 */
public class ProdConsumerDemo {

     public static void main(String[] args) {

        kt kt = new kt();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    kt.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    kt.sub();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}
class kt{
    private int number=0;

    public synchronized void add() throws InterruptedException {
        //1.判断
        if(number !=0){
            this.wait();
        }
        //2.干活
        number++;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //3.通知
        this.notify();
    }
    public synchronized  void sub() throws InterruptedException {
        //1.判断
        if(number ==0){
            this.wait();
        }
        //2.工作
        number--;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //3.通知
        this.notify();



    }


}




